package com.chinanet.controller.faultanticipate;

import com.chinanet.entry.faultanticipate.Model;
import com.chinanet.entry.faultanticipate.Operation;
import com.chinanet.message.entry.faultanticipate.OperationMessage;
import com.chinanet.repository.faultanticipate.DetailRepository;
import com.chinanet.repository.faultanticipate.ModelRepository;
import com.chinanet.repository.faultanticipate.OperationRepository;
import com.chinanet.service.faultanticipate.IOperationService;
import com.chinanet.service.faultanticipate.controll.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping(value = "/models/operation")
public class ModelController {

    @Resource
    private ModelRepository modelRepository;

    @Resource
    private ModelService modelService;
    @Resource
    private DetailRepository detailRepository;

    @Resource
    private OperationRepository operationRepository;

    @Autowired
    private IOperationService operationService;

    //模型上传
    @RequestMapping(value = "upload", method = POST)
    public void upload(Model model) {
        modelRepository.save(model);
    }

    //运行模型，是异步操作
    @RequestMapping(value = "{detailId}/{model}", method = POST)
    public long model(@PathVariable Long detailId, @PathVariable String model, @RequestBody String data) {
        Operation operation=operationService.init();
        System.out.println(detailId);
        modelService.execute(model, data, detailRepository.findById(detailId).get(),operation);
        return operation.getId();
    }
    //运行模型结果
    @MessageMapping("/result")
    @SendTo("/topic/model")
    public  Operation result(OperationMessage message) throws Exception{
        return operationRepository.findById(message.getOperationId()).get();
    }

    @MessageExceptionHandler
    @SendToUser(destinations = "/queue/errors",broadcast=false)
    public Exception result(Exception ex) throws Exception{
        return ex;
    }

    // 从服务端发送数据
    @RequestMapping(path="/result",method = POST)
    public void sendResult(long id){
       modelService.sendResult("/topic/model",id);
    }
}
